<?php
include_once('config/config.php');

if($_POST)
{
    // 接收参数
    $name = isset($_POST['name']) ? trim($_POST['name']) : '';
    $mobile = isset($_POST['mobile']) ? trim($_POST['mobile']) : '';
    $email = isset($_POST['email']) ? trim($_POST['email']) : '';
    $gender = isset($_POST['gender']) ? trim($_POST['gender']) : 0;
    // 地区区划码
    $code = isset($_POST['code']) ? trim($_POST['code']) : '';
    $address = isset($_POST['address']) ? trim($_POST['address']) : '';
    $depid = isset($_POST['depid']) ? trim($_POST['depid']) : '';
    $jobid = isset($_POST['jobid']) ? trim($_POST['jobid']) : '';

    if(empty($name))
    {
        notice('姓名不能为空');
    }

    if(empty($mobile))
    {
        notice('手机号不能为空');
    }

    // 手机号正则
    $MobileReg = '/^1[3-9]\d{9}$/';

    preg_match($MobileReg,$mobile,$MobileRes);
    
    if(!$MobileRes)
    {
        notice('手机号不正确');
    }

    if(empty($email))
    {
        notice('邮箱不能为空');
    }

    if(empty($address))
    {
        notice('详情地址不能为空');
    }

    // 组装插入数据
    $data = [
        'name' => $name,
        'mobile' => $mobile,
        'email' => $email,
        'gender' => $gender,
        'address' => $address,
        'createtime' => time(),
    ];

    // 地区
    $RegionSql = "SELECT `parentpath` FROM `pre_region` WHERE `code` = '$code'";

    $region = find($RegionSql);

    if(!$region)
    {
        notice('所选地区不存在');
    }

    // 把字符串转成数组
    $PathArr = explode(',',$region['parentpath']);

    $data['province'] = $PathArr[0] ?? Null;
    $data['city'] = $PathArr[1] ?? Null;
    $data['district'] = $PathArr[2] ?? Null;

    // 部门
    $DepInfoSql = "SELECT * FROM `pre_department` WHERE `id` = '$depid'";

    $DepInfo = find($DepInfoSql);

    if(!$DepInfo)
    {
        notice('所选部门不存在');
    }

    $data['depid'] = $depid;

    // 职位
    $JobInfoSql = "SELECT * FROM `pre_job` WHERE `id` = '$jobid'";

    $JobInfo = find($JobInfoSql);

    if(!$JobInfo)
    {
        notice('所选职位不存在');
    }

    $data['jobid'] = $jobid;

    $avatar = build_upload('avatar');

    if($avatar['code'] === 0)
    {
        notice($avatar['msg']);
    }

    $data['avatar'] = $avatar['data'];

    $result = add('person',$data);

    if($result['code'] === 1)
    {
        notice('添加成功','PersonList.php');
    }else{
        @is_file('.' . $avatar['data']) && unlink('.' . $avatar['data']);

        echo $result['msg'];
        exit;
    }
}


$DepSql = "SELECT * FROM `pre_department` ORDER BY `id` DESC";

$DepData = all($DepSql);
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <!-- 引入公共样式 -->
    <?php include_once('common/meta.php'); ?>

    <!-- 引入地区选择插件样式 -->
    <link rel="stylesheet" href="/assets/lib/city-picker/city-picker.css">

</head>

<body>
    <!-- 引入头部 -->
    <?php include_once('common/header.php'); ?>

    <!-- 引入公共菜单 -->
    <?php include_once('common/menu.php'); ?>

    <div class="content">
        <div class="header">
            <h1 class="page-title">添加员工</h1>
        </div>
        <ul class="breadcrumb">
            <li><a href="index.php">Home</a> <span class="divider">/</span></li>
            <li class="active">PersonAdd</li>
        </ul>

        <div class="container-fluid">
            <div class="row-fluid">

                <div class="btn-toolbar">
                    <button class="btn btn-primary" onClick="location='PersonList.php'"><i class="icon-list"></i> 员工列表</button>
                    <div class="btn-group">
                    </div>
                </div>

                <div class="well">
                    <div id="myTabContent" class="tab-content">
                        <div class="tab-pane active in" id="home">
                            <form method="post" enctype="multipart/form-data">
                                <label>员工姓名</label>
                                <input type="text" name="name" placeholder="员工姓名" class="input-xxlarge">
                            
                                <label>手机号</label>
                                <input type="text" name="mobile" placeholder="手机号" class="input-xxlarge">

                                <label>邮箱</label>
                                <input type="email" name="email" placeholder="邮箱" class="input-xxlarge">

                                <label>性别</label>
                                <select name="gender" class="input-xxlarge">
                                    <option value="0">保密</option>
                                    <option value="1">男</option>
                                    <option value="2">女</option>
                                </select>

                                <div style="position: relative;height:55px;">
                                    <label>地区</label>
                                    <input type="text" id="region" data-toggle="city-picker" readonly class="input-xxlarge">

                                    <input type="hidden" name="code" id="code">
                                </div>

                                <label>详细地址</label>
                                <input type="text" name="address" placeholder="详情地址" class="input-xxlarge">
                                
                                <label>部门</label>
                                <select name="depid" class="input-xlarge" id="depid">
                                    <option value="0">请选择</option>
                                    <?php foreach($DepData as $item){ ?>
                                        <option value="<?php echo $item['id'];?>"><?php echo $item['name']; ?></option>
                                    <?php }?>
                                </select>

                                <label>职位</label>
                                <select name="jobid" class="input-xlarge" id="jobid">
                                    <option value="0">请选择</option>
                                </select>

                                <label>头像</label>
                                <input type="file" name="avatar" id="avatar" hidden class="input-xxlarge">
                                <img style="width: 200px;height:200px;object-fit:cover;" src="/assets/images/upload.png" id="upload" alt="">
                            
                                <label></label>
                                <input class="btn btn-primary" type="submit" value="提交" />
                            </form>
                        </div>
                    </div>
                </div>

                <!-- 引入公共底部 -->
                <?php include_once('common/footer.php'); ?>

            </div>
        </div>
    </div>

</body>

</html>

<!-- 引入地区数据 -->
<script src="/assets/lib/city-picker/city-picker.data.min.js"></script>
<!-- 引入地区选择插件js -->
<script src="/assets/lib/city-picker/city-picker.min.js"></script>

<script>
    $('#depid').change(function(){
        let depid = $(this).val();

        if(depid == 0)
        {
            // 职位下拉选择框的内容清空
            $('#jobid').html(`<option value="0">请选择</option>`);

            return false;
        };

        $.ajax({
            type:'post',
            url:'api.php',
            data:{
                depid,
                action:'select_job'
            },
            dataType:'json',
            success:(result) =>
            {
                if(result.code === 1)
                {
                    let html = '';

                    for(let item of result.data)
                    {
                        html += `<option value="${item.id}">${item.name}</option>`;
                    }

                    $('#jobid').html(html);
                }else{
                    $('#jobid').html(`<option value="0">暂无职位</option>`);
                }
            }
        })
    })

    $('#upload').click(function(){
        $('#avatar').click();
    })

    $('#avatar').change(function(){
        let file = this.files[0] ?? '';

        if(file)
        {
            let Reader = new FileReader();

            Reader.readAsDataURL(file);

            Reader.onload = function()
            {
                $('#upload').attr('src',Reader.result);
            }
        }
    })

    $("#region").on("cp:updated", function() {
        let citypicker = $(this).data("citypicker");
        let code = citypicker.getCode("district") || citypicker.getCode("city") || citypicker.getCode("province");
        $("#code").val(code);
    });
</script>